import { defineStore } from 'pinia';
import { computed, ref, watch } from 'vue';
import { loginUser, registerUser } from '../api/demo';

const STORAGE_KEY = 'course_app_user_v1';

const normalizeUser = (payload) => {
  if (!payload || typeof payload !== 'object') return null;
  const id =
    payload.id ??
    payload.userid ??
    payload.userId ??
    payload.userID ??
    payload.user_id ??
    payload.uid ??
    payload.ID ??
    payload.user_id_pk;
  return { ...payload, id };
};

const extractUserFromResponse = (raw) => {
  if (!raw) return null;

  if (Array.isArray(raw)) {
    if (!raw.length) return null;
    return extractUserFromResponse(raw[0]);
  }

  if (typeof raw === 'string') {
    try {
      const parsed = JSON.parse(raw);
      return extractUserFromResponse(parsed);
    } catch (error) {
      return null;
    }
  }

  if (typeof raw === 'object') {
    const direct = normalizeUser(raw);
    if (direct?.id) {
      return direct;
    }

    const candidateKeys = ['data', 'result', 'rows', 'list', 'user', 'userinfo', 'record'];
    for (const key of candidateKeys) {
      if (raw[key] !== undefined && raw[key] !== null) {
        const nested = extractUserFromResponse(raw[key]);
        if (nested?.id) {
          return nested;
        }
      }
    }

    return direct;
  }

  return null;
};

export const useAuthStore = defineStore('auth', () => {
  const stored = localStorage.getItem(STORAGE_KEY);
  const user = ref(stored ? JSON.parse(stored) : null);

  watch(
    user,
    (val) => {
      if (!val) {
        localStorage.removeItem(STORAGE_KEY);
        return;
      }
      localStorage.setItem(STORAGE_KEY, JSON.stringify(val));
    },
    { deep: true }
  );

  const isLoggedIn = computed(() => Boolean(user.value && (user.value.id ?? user.value.userid)));
  const username = computed(() => user.value?.username || '');

  const login = async (credentials) => {
    const data = await loginUser(credentials);
    if (!data) {
      throw new Error('登录失败，请检查用户名或密码');
    }

    const parsedUser = extractUserFromResponse(data);
    if (!parsedUser?.id) {
      throw new Error('登录失败，请检查用户名或密码');
    }

    user.value = parsedUser;
    return user.value;
  };

  const register = async (payload) => {
    return registerUser(payload);
  };

  const logout = () => {
    user.value = null;
  };

  const ensureAuth = () => {
    if (!isLoggedIn.value) {
      throw new Error('请先登录后再执行此操作');
    }
  };

  return {
    user,
    username,
    isLoggedIn,
    login,
    register,
    logout,
    ensureAuth,
  };
});
